<?php

namespace app\backend\controller;

use think\Controller;
use think\exception\PDOException;
use think\Request;
use app\backend\model\Module as ModuleModel;
use app\backend\model\Role as RoleModel;

class Role extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 获取用户组信息
        $roleList = RoleModel::all();
        $count = RoleModel::count();

        return view('/role/list', [
            'count' => $count,
            'roleList' => $roleList,
        ]);
    }

    /**
     * 显示创建资源表单页.
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function create(Request $request)
    {
        //加载角色新建页面
        $method = $request->method();
        if ($method == "GET")
        {
            $module = ModuleModel::all();
            return view('/role/add', [
                'module' => $module,
            ]);
        }

        //提交数据
        $role = new RoleModel();
        $role->name = input('name');
        $role->comments = input('comments');
        $role->node = input('node');

        try{
            $role->save();
            $status = 200;  //数据发送成功
            $message = '用户组添加成功';
        }catch (PDOException $e){
            $status = 202;  //数据发送失败
            $message = $e->getMessage();
        }

        return json(['status' => $status, 'message' => $message]);

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        // 获取需要修改的用户组别信息
        $role = RoleModel::get($id);

        //获取模块列表信息
        $module = ModuleModel::all();
        return view('/role/edit', [
            'role' => $role,
            'module' => $module,
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //获取需要更新的用户组信息
        $role = RoleModel::get($id);

        //获取修改数据
        $data = $request->post();

        try {
            $role->save($data);
            $msg = "更新成功";
        } catch (PDOException $e) {
            $msg = $e->getMessage();
        }

        return json(["message" => $msg]);

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }


    /**
     * 角色权限管理
     * @return \think\response\View
     *
     */
    public function permission()
    {
        return view('/role/permission');
    }
}
